<template>
  <div>
    <!-- 录入按钮 -->
    <div class="toAdd">
      <el-row type="flex" justify="">
        <!-- 不用浮动对性能损耗小 -->
        <el-col :span="20" style="height: 32px"></el-col>
        <el-col :span="4" style="text-align: right">
          <el-button type="primary" @click="toAdd">录入</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 表格数据 -->
    <div class="table">
      <el-table :data="engData" style="width: 100%">
        <el-table-column type="index" :index="1" label="序号" width="80px">
        </el-table-column>
        <el-table-column prop="serial_number" label="编号" width="180px">
        </el-table-column>
        <el-table-column prop="name" label="名称" width="380px">
        </el-table-column>
        <el-table-column prop="type" label="工程类型"> </el-table-column>
        <el-table-column prop="status" label="状态">
          <template v-slot="scope">
            <div>
              <el-tag type="success" v-if="scope.row.status === '监测中'"
                >监测中</el-tag
              >
              <el-tag v-else-if="scope.row.status === '未绑定'" type="warning"
                >未绑定</el-tag
              >
              <el-tag v-else type="danger">已结束</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <!-- 作用域插槽，对当前行信息进行数据获取 -->
          <template v-slot="scope">
            <div>
              <el-button type="text" @click="toEdit(scope.row)">修改</el-button>
              <el-button
                type="text"
                v-if="scope.row.status === '已结束'"
                disabled
                >绑定</el-button
              >
              <el-button
                @click="toDetails(scope.row)"
                type="text"
                v-if="
                  scope.row.status === '监测中' || scope.row.status === '未绑定'
                "
                >绑定</el-button
              >
              <el-button type="text" v-if="scope.row.status === '监测中'"
              @click="tofinish(scope.row.id)"
                >结束</el-button
              >
              <el-button
                type="text"
                v-if="
                  scope.row.status === '未绑定' || scope.row.status === '已结束'
                "
                disabled
                >结束</el-button
              >
              <el-button
                type="text"
                v-if="scope.row.status === '未绑定'"
                @click="toDelete(scope.row.id)"
                >删除</el-button
              >
              <el-button
                type="text"
                v-if="
                  scope.row.status === '监测中' || scope.row.status === '已结束'
                "
                disabled
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页按钮 -->
    <div class="page" style="margin-top: 15px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.page"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="text-align: left"
        hide-on-single-page
      >
      </el-pagination>
    </div>
    <!-- 模态框 -->
    <!-- 抽屉 -->
    <!-- close抽屉事件 关闭模态框做什么事 -->
    <el-drawer
      size="50%"
      @close="toClose"
      :title="title"
      :visible.sync="dialog"
      direction="rtl"
      custom-class="demo-drawer"
      ref="drawer"
    >
      <div class="demo-drawer__content">
        <!-- 表单 -->
        <el-form :model="form" :rules="rules" ref="myForm">
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="编号"
                prop="serial_number"
                :label-width="formLabelWidth"
              >
                <el-input
                  v-model="form.serial_number"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="名称"
                prop="name"
                :label-width="formLabelWidth"
              >
                <el-input v-model="form.name" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="工程类型"
                prop="type"
                :label-width="formLabelWidth"
              >
                <el-select
                  clearable
                  v-model="form.type"
                  placeholder="请选择工程类型"
                >
                  <el-option label="园区" value="园区"></el-option>
                  <el-option label="写字楼" value="写字楼"></el-option>
                  <el-option label="建筑工地" value="建筑工地"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="区域经理"
                prop="charge_id"
                :label-width="formLabelWidth"
              >
                <el-select
                  clearable
                  v-model="form.charge_id"
                  placeholder="请选择区域经理"
                >
                  <el-option
                    v-for="item in cData"
                    :key="item.id"
                    :label="item.realname"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="经度"
                prop="longitude"
                :label-width="formLabelWidth"
              >
                <el-input
                  v-model="form.longitude"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="纬度"
                prop="latitude"
                :label-width="formLabelWidth"
              >
                <el-input v-model="form.latitude" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="地址"
                prop="address1"
                :label-width="formLabelWidth"
              >
                <el-cascader
                  v-model="form.address1"
                  :props="{
                    value: 'name',
                    label: 'name',
                  }"
                  :options="options"
                  clearable
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="详细地址"
                prop="address2"
                :label-width="formLabelWidth"
              >
                <el-input v-model="form.address2" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="客户姓名"
                prop="customer_name"
                :label-width="formLabelWidth"
              >
                <el-input
                  v-model="form.customer_name"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="客户电话"
                prop="customer_telephone"
                :label-width="formLabelWidth"
              >
                <el-input
                  v-model="form.customer_telephone"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="dialog = false">取 消</el-button>
          <el-button type="primary" @click="toSave">确定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { get, postJSON, del } from "@/utils/request";
// 引入省市区的数据
import pca from "@/assets/pca.json";
export default {
  data() {
    return {
      // 校验规则 必填项
      rules: {
        serial_number: [
          { required: true, message: "请输入工程编号", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入工程名称", trigger: "blur" }],
        type: [
          { required: true, message: "请选择工程类型", trigger: "change" },
        ],
        charge_id: [
          { required: true, message: "请选择区域经理", trigger: "change" },
        ],
        longitude: [{ required: true, message: "请输入经度", trigger: "blur" }],
        latitude: [{ required: true, message: "请输入纬度", trigger: "blur" }],
        address1: [
          { required: true, message: "请选择地址", trigger: "change" },
        ],
        address2: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
        customer_name: [
          { required: true, message: "请输入客户姓名", trigger: "blur" },
        ],
        customer_telephone: [
          { required: true, message: "请输入客户手机号", trigger: "blur" },
        ],
      },
      // 工程数据
      engData: [],
      // 分页数据
      params: {
        page: 1,
        pageSize: 5,
      },
      // 页面数据总数
      total: 0,
      // 抽屉标题
      title: "",
      // 控制抽屉的隐藏与显示
      dialog: false,
      // 表单对象
      form: {},
      // 表单文字宽度
      formLabelWidth: "80px",
      // 级联选择器的配置项
      options: pca,
      // 区域经理信息
      cData: [],
    };
  },
  methods: {
    // 绑定操作 跳转到工程详情页面
    toDetails(row) {
      // 路由跳转 并传参
      this.$router.push({
        path: "/am/engineer/Details",
        query: row
      });
    },
    // 删除操作 删除未绑定功能
    toDelete(id) {
      this.$confirm("此操作将删除该工程, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 发送删除请求
          let res = await del("/engineer/deleteById", {
            id: id,
          });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          // 将页码改为1
          this.params.page = 1;
          // 重新请求工程数据
          this.getEngData();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 关闭模态框，清空表单校验
    toClose() {
      this.$refs["myForm"].resetFields();
      this.dialog = false;
    },
    // 获取区域经理
    async getCData() {
      let res = await get("/user/pageQuery", {
        page: 1,
        pageSize: 1000,
        role_id: 3,
      });
      // console.log(res);
      this.cData = res.data.list;
    },
    // 去提交
    toSave() {
      // ref 一个对象，属性是myForm 可以用.访问也可以用[]访问
      this.$refs["myForm"].validate(async (valid) => {
        // 校验通过
        if (valid) {
          // alert('submit!');
          // console.log(this.form);
          // 深拷贝
          let obj = { ...this.form };
          obj.address = obj.address1.join("") + obj.address2;
          // 删除不需要数据
          delete obj.address1;
          delete obj.address2;
          // console.log(obj);
          // 发送更新请求
          let res = await postJSON("/engineer/saveOrUpdate", obj);
          if (res.status === 200) {
            this.$notify({
              title: "成功",
              message: res.message,
              type: "success",
            });
            // 清空表单校验
            this.toClose();
            this.getEngData();
          } else {
            this.$notify({
              title: "失败",
              message: res.message,
              type: "error",
            });
          }
          // 关闭抽屉
          this.dialog = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 去修改
    toEdit(row) {
      

      // console.log(row, "row");
      this.dialog = true;
      this.title = "修改工程信息";
      // 深拷贝
      this.form = { ...row }; //
    },
    // 去录入
    toAdd() {
      // 弹出抽屉
      this.dialog = true;
      // 修改标题
      this.title = "录入工程信息";
      // 去清空
      this.form = {};
    },
    // 获取工程数据
    async getEngData() {
      let res = await get("/engineer/pageQuery", this.params);
      // console.log(res);
      this.engData = res.data.list;
      this.total = res.data.total;
    },
    // 数据条数发生变化的处理函数
    handleSizeChange(pageSize) {
      // console.log(pageSize,'条数');
      this.params.pageSize = pageSize;
      this.getEngData();
    },
    // 页码发生改变的函数
    handleCurrentChange(page) {
      // console.log(page,'当前页码');
      this.params.page = page;
      this.getEngData();
    },
    // 去结束
    tofinish(id){
      this.$confirm("工程结束后将自动解绑设备, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 发送结束工程请求
          let res = await get("/engineer/finish", {
            id: id,
          });
          this.$message({
            type: "success",
            message: "结束成功!",
          });
          // 将页码改为1
          this.params.page = 1;
          // 重新请求工程数据
          this.getEngData();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消结束",
          });
        });
    }
  },
  created() {
    this.getEngData();
    // 获取区域经理数据
    this.getCData();
  },
};
</script>